import {createSlice, createAsyncThunk} from '@reduxjs/toolkit';
import {fetchPopularRepo} from '../api/popular';
import {setStorage, getStorage, removeStorage} from '../utils/storage';
import isEmpty from 'lodash/isEmpty';

const storeKey = 'get/fetchPopular';

export const fetchPopular = createAsyncThunk(storeKey, res => {
  return getStorage(storeKey).then(value => {
    const {data = {}, time} = value || {};
    const now = new Date().getTime();

    if (isEmpty(data[res.key]) || now - time > 60 * 60 * 1000 || res.refresh) {
      if (!isEmpty(data[res.key])) {
        removeStorage(storeKey);
      }
      return fetchPopularRepo(res.type);
    }
    return data;
  });
});

const popularReducer = createSlice({
  name: 'popular',
  initialState: {
    popularData: {},
    refresh: false,
  },
  reducers: {
    changePopularData(state, action) {
      const {item, key} = action.payload;
      state.popularData[key] = state.popularData[key].map(i =>
        i.id === item.id ? item : i,
      );
    },
  },
  extraReducers(builder) {
    builder
      .addCase(fetchPopular.pending, (state, action) => {
        const {refresh} = action.meta.arg;
        if (refresh) {
          state.refresh = true;
        }
      })
      .addCase(fetchPopular.fulfilled, (state, action) => {
        const {key, refresh} = action.meta.arg;
        const {items} = action.payload;
        const prevPopularData = state.popularData;
        state.popularData = {
          ...prevPopularData,
          [key]: items,
        };
        if (refresh) {
          state.refresh = false;
        }

        setStorage(storeKey, {
          data: state.popularData,
          time: new Date().getTime(),
        });
      })
      .addCase(fetchPopular.rejected, (state, action) => {
        const {refresh} = action.meta.arg;
        if (refresh) {
          state.refresh = false;
        }
      });
  },
});

export const {changePopularData} = popularReducer.actions;
export default popularReducer.reducer;
